package com.XZDP.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.XZDP.dto.Result;
import com.XZDP.entity.Voucher;
import com.XZDP.entity.VoucherOrder;
import com.XZDP.mapper.VoucherOrderMapper;
import com.XZDP.service.ISeckillVoucherService;
import com.XZDP.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.XZDP.service.IVoucherService;
import com.XZDP.utils.RedisID;
import com.XZDP.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private IVoucherService iVoucherService;
    @Autowired
    private VoucherOrderMapper voucherOrderMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ISeckillVoucherService iSeckillVoucherService;
    @Autowired
    private RedisID redisID;//全局唯一ID生成器
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    private static final DefaultRedisScript<Long> SECKLL_SCRIPT;
    //基于JVM的阻塞队列
    private static final BlockingQueue<VoucherOrder> blockingqueue = new ArrayBlockingQueue<>(5000);
    //代理对象初始化,便于子线程使用
    private static IVoucherOrderService proxy;
    //线程池
    private static final ExecutorService threadPool = Executors.newSingleThreadExecutor();
    //消息队列名称
    private static final String QUEUE_NAME = "stream.orders";

    static {
        SECKLL_SCRIPT = new DefaultRedisScript<>();
        SECKLL_SCRIPT.setLocation(new ClassPathResource("seckill_MQ.lua"));
        SECKLL_SCRIPT.setResultType(Long.class);
    }

    //加载该类时就执行
//    @PostConstruct
//    private void init() throws Exception {
//        //提交线程任务
//        threadPool.submit(new Thread_VoucherOrder());
//    }
//
//    //构建线程池实现类实现异步下单逻辑
//    private class Thread_VoucherOrder implements Runnable {
//        @Override
//        public void run() {
//            //死循环监听消息队列
//            while (true) {
//                //读取消息队列中的消息
//                //List<MapRecord<K, HK, HV>> read(Consumer var1, StreamReadOptions var2, StreamOffset<K>... var3);
//                List<MapRecord<String, Object, Object>> ResultRead = redisTemplate.opsForStream().read(
//                        Consumer.from("g0", "c1"),//指定消费者组和消费者
//                        StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),//指定阻塞等待时间和读取消息条数
//                        StreamOffset.create(QUEUE_NAME, ReadOffset.lastConsumed())//指定消息队列名称和读取标识
//                );
//                if (ResultRead == null || ResultRead.isEmpty()) {
//                    //返回值为空,队列中无消息,继续循环
//                    continue;
//                }
//                //队列中有消息,处理消息
//                try {
//                    //获取队列消息
//                    MapRecord<String, Object, Object> entries = ResultRead.get(0);
//                    Map<Object, Object> value = entries.getValue();
//                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
//                    proxy.getPeopleCount(voucherOrder);
//                    //处理完后确认消息
//                    redisTemplate.opsForStream().acknowledge(QUEUE_NAME, "g0", entries.getId());
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    log.info("订单处理异常");
//                    while (true) {
//                        //读取pending-list队列中的消息
//                        List<MapRecord<String, Object, Object>> PendingRead = redisTemplate.opsForStream().read(
//                                Consumer.from("g0", "c1"),//指定消费者组和消费者
//                                StreamOffset.create(QUEUE_NAME, ReadOffset.from("0"))//指定消息队列名称和读取标识
//                        );
//                        if (PendingRead == null || PendingRead.isEmpty()) {
//                            //返回值为空,队列中无消息,退出循环
//                            break;
//                        }
//                        //pending-list队列中有消息,处理消息
//                        try {
//                            //获取队列消息
//                            MapRecord<String, Object, Object> pendingEntries = PendingRead.get(0);
//                            Map<Object, Object> pendingValue = pendingEntries.getValue();
//                            VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(pendingValue, new VoucherOrder(), true);
//                            proxy.getPeopleCount(voucherOrder);
//                            //处理完后确认消息
//                            redisTemplate.opsForStream().acknowledge(QUEUE_NAME, "g0", pendingEntries.getId());
//                        } catch (Exception f) {
//                            f.printStackTrace();
//                            log.info("pending-list订单处理异常");
//                            try {
//                                Thread.sleep(10);
//                            } catch (InterruptedException ex) {
//                                throw new RuntimeException(ex);
//                            }
//                        }
//                    }
//                }
//            }
//        }
//    }

    //异步秒杀,基于LUA脚本确保原子性,采用redis Stream结构存储信息
//    public Result OrderSeckill(Long voucherId) {
//        //LUA脚本逻辑
//        //生成全局唯一ID
//        Long l = redisID.GetID("voucherOrder");
//        proxy = (IVoucherOrderService) AopContext.currentProxy();
//        Long execute = redisTemplate.execute(SECKLL_SCRIPT,
//                Collections.emptyList(),
//                String.valueOf(voucherId),
//                String.valueOf(UserHolder.getUser().getId()),
//                String.valueOf(l));
//        log.info(execute.toString());
//        if (execute == 1L) {
//            return Result.fail("库存不足");
//        }
//        if (execute == 2L) {
//            return Result.fail("您只能下一单");
//        }
//        return Result.ok(l);
//    }
//TODO 消费者失败后相关完善
    //RabbitMQ实现异步下单
    public Result OrderSeckill(Long voucherId) {
        //LUA脚本逻辑
        //生成全局唯一ID
        Long l = redisID.GetID("voucherOrder");
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        Long execute = redisTemplate.execute(SECKLL_SCRIPT,
                Collections.emptyList(),
                String.valueOf(voucherId),
                String.valueOf(UserHolder.getUser().getId()),
                String.valueOf(l));
        log.info(execute.toString());
        if (execute == 1L) {
            return Result.fail("库存不足");
        }
        if (execute == 2L) {
            return Result.fail("您只能下一单");
        }
        //将订单信息存入消息队列
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(l);
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        rabbitTemplate.convertAndSend("XZ.Order", "VoucherOrder", voucherOrder);
        return Result.ok(l);
    }

    //监听器
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "XZ.Order.queue1", durable = "true"),
            exchange = @Exchange(value = "XZ.Order"),
            key = {"VoucherOrder"}
    ))
    private void order(VoucherOrder voucherOrder) {
        proxy.getPeopleCount(voucherOrder);
    }

    //分布式锁非异步秒杀(性能差)
//    public Result OrderSeckill(Long voucherId) {
//        //判断秒杀是否开始
//        SeckillVoucher seckillVoucher = iSeckillVoucherService.getById(voucherId);
//        LocalDateTime now = LocalDateTime.now();
//        if (!now.isAfter(seckillVoucher.getBeginTime()) || !now.isBefore(seckillVoucher.getEndTime())) {
//            //不符合时间区间
//            return Result.fail("秒杀时间未开始");
//        }
//        //判断库存是否充足
//        if (seckillVoucher.getStock() == 0) {
//            return Result.fail("库存不足");
//        }
//        //SeckillVoucher seckillVoucher1 = new SeckillVoucher();
//        //BeanUtil.copyProperties(seckillVoucher, seckillVoucher1);
//        //seckillVoucher1.setStock(seckillVoucher.getStock() - 1);
//        //满足条件,开始下单
//        // iSeckillVoucherService.updateById(seckillVoucher1);
//        //获取当前用户ID
//        Long userid = UserHolder.getUser().getId();
//        // 使用用户ID加锁
//        // synchronized (userid.toString().intern()) {
//        // 获取代理对象
//        // IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//        // return proxy.getPeopleCount(voucherId);
//        // }
//        //获取redis分布式锁
//        //ILOCK ilock = new ILOCKlmpl(redisTemplate, "Order" + userid);
//        //基于redisson实现分布式锁
//        RLock ilock = redissonClient.getLock("Order" + userid);
//        //可重入锁
//        boolean b = ilock.tryLock();
//        if (!b) {
//            //获取锁失败
//            return Result.fail("非法操作");
//        }
//        try {
//            //获取代理对象
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.getPeopleCount(voucherId);
//        } finally {
//            ilock.unlock();
//        }
//    }
    @Transactional
    public void getPeopleCount(VoucherOrder voucherOrder) {
        //获取当前用户ID
        Long userid = voucherOrder.getId();
        //乐观锁解决超卖问题
        //修改库存
        boolean update = iSeckillVoucherService.update().setSql("stock = stock -1")
                .eq("voucher_id ", voucherOrder.getVoucherId()).gt("stock", 0).update();
        if (!update) {
            log.error("库存不足");
        }
        voucherOrderMapper.insert(voucherOrder);
    }
}
